<script lang="ts">
	import { goto } from "$app/navigation";
	import { getChannelVideo, type LZIZY_Video } from "../lib/api/lzizy/interface";
	import VideoList from "../components/VideoList.svelte";
	import { appState } from "../stores/state.svelte";
  import { set, get, has, remove, clear, stats, CompressionMethod } from 'tauri-plugin-cache-api'


	const CHANNEL_LIST = ["电影", "电视剧", "动漫", "综艺"];
	const CACHE_TIME = 259200;

	$effect(() => {
		loadChannelData(appState.channelIndex);
		// $inspect(appState.channelIndex);
		// $inspect(appState.channelList[appState.channelIndex]);
		// $inspect(appState.playItem);
	})

	async function loadChannelData(channelIndex: number) {
		let key = `channel[${appState.channelIndex}]`;
		console.log(`[正在检查缓存] ${key}`);
		
		if(await has(key)) {
			console.log(`[正在获取缓存] ${key}`);
			let cacheData = await get<LZIZY_Video[]>(key);
			if(cacheData !== null)	{
				console.log("[已成功读取缓存数据]");
				appState.channelList[appState.channelIndex] = cacheData;
				return;
			}
		} else {
			console.log("[缓存不存在]");
			getChannelVideo(channelIndex).then((value) => {
				appState.channelList[channelIndex] = value;
				console.log("[正在缓存]");
				set(key, value,{ttl: CACHE_TIME, compress: false, compressionMethod: CompressionMethod.Zlib})
				console.log("[已缓存]");
			});
		}
	}

	async function on_Click_ChannelList(index: number) {
		appState.playItem = appState.channelList[appState.channelIndex][index];
		await goto("/info");
	}
</script>

<main>
	<div class="channel-bar">
		{#each CHANNEL_LIST as value, index}
			<div class="item" style:background-color={index == appState.channelIndex ? "rgba(255, 255, 255, 0.27)" : "transparent"} onclick={() => appState.channelIndex = index}>
				<p>{value}</p>
			</div>
		{/each}
	</div>
	
	<VideoList data={appState.channelList[appState.channelIndex].slice(0)} onClick={on_Click_ChannelList} />
</main>

<style lang="scss">
	main {
		height: 100%;
		display: grid;
		grid-template-rows: 40px 1fr;
		overflow: hidden;
	}
	
	.channel-bar {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		
		.item {
			display: flex;
			&:hover {
				background-color: rgba(255, 255, 255, 0.27);
			}
			p {
				margin: auto;
			}
		}
	}
</style>